<template>
  <div class="car">
    <!-- 车辆列表 -->

    <div class="task_header">
      <div class="top_title">
        <div class="top_title_back" @click="$router.go(-1)">
          <i class="iconfont icon-back"></i>
        </div>
        <div class="top_title_val">{{ $route.meta.title }}</div>
      </div>
    </div>
    <div class="carList mt" v-if="fileList && fileList.length">
      <div class="carItem flex" v-for="(item, index) in fileList" :key="index">
        <div class="file_lt">
          <i class="iconfont icon-file"></i>
          {{ item.ATTNAME }}
        </div>
        <i v-if="!item.downTxt" @click="downloadFile(item)" class="iconfont icon-download"></i>
        <span class="downTxt" v-else>{{ item.downTxt }}</span>
      </div>
    </div>
    <div :class="['carList', (!fileList || fileList.length === 0) ? 'mt' : '']" v-if="newFiles && newFiles.length">
      <div class="carItem flex" v-for="(item, index) in newFiles" :key="index">
        <div class="file_lt">
          <i class="iconfont icon-file"></i>
          {{ item.name }}
        </div>
        <van-icon name="clear" color="#cecece" size="20px" @click="delData(item, index)" />
      </div>
    </div>
    <van-empty class="noContent" description="暂无数据" v-if="fileList.length == 0 && newFiles.length == 0" />
    <div class="footer">
      <div class="footerBtn flex">
        <div class="btnType selBtn">
          选择文件
          <input type="file" @change="getFiles" multiple="multiple" class="file_ipt" />
        </div>
        <div class="btnType uploadBtn" @click="referFile" :class="{ disable_btn: newFiles.length == 0 }">立即上传</div>
      </div>
    </div>
  </div>
</template>

<script>
import { Empty, Toast, Dialog, Notify } from 'vant'
const base_url = process.env.BASE_API
import commonApi from '@/api/commonApi'
import commJs from '@/assets/js/commJs'
import axios from 'axios'

export default {
  name: 'fileMange',
  components: {
    Empty,
    Dialog,
  },
  data() {
    return {
      fileList: [],
      newFiles: [],
      fileData: new FormData(),
      billId: '',
      billType: 'CarInfo',
    }
  },

  mounted() {
    if (this.$route.query && this.$route.query.billId) {
      this.billId = this.$route.query.billId
      this.getFileList(this.$route.query.billId)
    }
    if (this.$route.query && this.$route.query.billType) {
      this.billType = this.$route.query.billType
    }
    console.log('base_url', base_url)
  },
  methods: {
    getFileList(billId) {
      commonApi.getFileList({ billId }).then((res) => {
        console.log(res)
        res.records &&
          res.records.map((item) => {
            item.downTxt = ''
            item.progress = null
          })
        this.fileList = res.records
        console.log(this.newFiles)
      })
    },
    dataURLtoFile(dataurl, filename) {
      // base64转file
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, {
        type: mime,
      })
    },
    canvasDataURL(path, objCompressed, callback) {
      // 压缩图片
      var img = new Image()
      var _this = this
      img.src = path
      img.onload = function () {
        var that = this
        // 默认压缩后图片规格
        var quality = 0.5
        var w = that.width
        var h = that.height
        var scale = w / h

        // 判断图片是竖的还是横的
        if (w < h) {
          w = h
          _this.trans = true
        }

        // 实际要求
        w = objCompressed.width || w
        h = objCompressed.width / scale || w / scale

        if (objCompressed.quality && objCompressed.quality > 0 && objCompressed.quality <= 1) {
          quality = objCompressed.quality
        }

        // 生成canvas
        var canvas = document.createElement('canvas')
        var ctx = canvas.getContext('2d')
        // 创建属性节点
        var anw = document.createAttribute('width')
        anw.nodeValue = w
        var anh = document.createAttribute('height')
        anh.nodeValue = h
        canvas.setAttributeNode(anw)
        canvas.setAttributeNode(anh)
        ctx.drawImage(that, 0, 0, w, h)

        var base64 = canvas.toDataURL('image/jpeg', quality)
        // 回调函数返回base64的值
        callback(base64)
      }
    },
    // 上传文件处理
    getFiles(e, index, j) {
      const files = e.target.files
      const _this = this
      console.log(files)
      if (files.length >= 10) {
        Toast('一次最多只能上传10个文件')
        return false
      }
      for (var i = 0; i < files.length; i++) {
        const data = {
          file: files[i],
          name: files[i].name.slice(0, files[i].name.lastIndexOf('.')),
          suffix: files[i].name.slice(files[i].name.lastIndexOf('.')),
        }
        _this.newFiles.unshift(data)
        console.log(_this.newFiles)
      }
    },
    delData(data, index) {
      data.name = ''
      this.newFiles.splice(index, 1)
    },
    // 提交附件
    referFile() {
      const _this = this
      const files = _this.newFiles

      if (_this.newFiles.length == 0) {
        return false
      }

      for (let i = 0; i < files.length; i++) {
        const url = ''
        if (files[i].name == '') {
          Toast('文件名不能为空')
          return false
        }
        if (files[i].file.type.split('/')[1] != 'image') {
          // 非图片
          if (files[i].file.size > 5242880) {
            Toast('文件不得大于5M')
            return false
          }
          _this.fileData.append('files', files[i].file, files[i].name + files[i].suffix)
        } else {
          var reader = new FileReader()
          reader.readAsDataURL(files[i].file)
          reader.onload = function (e) {
            _this.canvasDataURL(
              this.result,
              {
                quality: 0.2,
              },
              function (base64Codes) {
                var file = _this.dataURLtoFile(base64Codes, files[i].name)

                _this.fileData.append('files', file, files[i].name) // 文件对象
              }
            )
          }
        }
      }
      Dialog.confirm({
        title: '确定上传？',
        message: `确定上传${_this.newFiles.length}个文件？`,
      })
        .then(() => {
          Toast.loading({
            message: '上传中...',
            forbidClick: true,
            duration: 0, // 手动关闭
          })
          _this.fileData.append('billType', _this.billType)
          _this.fileData.append('billId', encodeURI(_this.billId))
          console.info(_this.fileData)

          const base_url = process.env.BASE_API
          axios.post(base_url + '/proxy/cam/file/uploadFiles', _this.fileData, {
            headers: {
              'Content-Type': 'application/json;charset=UTF-8',
              'satoken': localStorage.getItem('token')
            }
          }).then(res => {
            Toast.clear()
            if (res.data && res.data.success) {
              Notify({ type: 'success', message: '上传成功' })
              _this.fileData.delete('files')
              _this.fileData.delete('billType')
              _this.fileData.delete('billId')
              _this.newFiles = []
              _this.getFileList(this.billId)
            } else {
              Notify({ type: 'danger', message: '上传失败' })
            }

          }).catch((err) => {
            Toast.clear()
            Notify({ type: 'danger', message: '上传异常，请稍后重试' })
          })

          // commonApi.uploadFiles(_this.fileData).then((res) => {
          //   console.log(res)
          //   Toast.clear()
          //   if (res.data.errcode == 0) {
          //
          //     Notify({ type: 'success', message: '上传成功' })
          //
          //     _this.fileData.delete('files')
          //     _this.fileData.delete('billType')
          //     _this.fileData.delete('billId')
          //     _this.newFiles = []
          //     _this.getlistFiles()
          //   } else {
          //     Notify({ type: 'danger', message: '上传失败' })
          //   }
          // }).catch((err) => {
          //   Toast.clear()
          //   Notify({ type: 'danger', message: '上传异常，请稍后重试' })
          // })
        })
        .catch(() => {
          _this.fileData.delete('files')
          _this.fileData.delete('billType')
          _this.fileData.delete('billId')
        })
    },
    // 下载文件
    downloadFile(data) {
      console.log(data)
      const formData = {
        attachId: encodeURI(data.ATTID),
        attachName: data.ATTNAME,
      }
      const _this = this
      var link = document.createElement('a')

      if (data.fileName && commJs.testPlat() == 1) {
        link.href = `${base_url}/download/${data.fileName}`
        link.download = data.fileName
        link.click()
        URL.revokeObjectURL(link.href)
        return false
      }
      // if (this.lock) {
      //   return false
      // }

      data.progress = data.progress | 0
      if (data.progress == 100 && commJs.testPlat() == 0) {
        Toast('该文件已下载，请勿重复下载！')
        return false
      } else {
        data.downTxt = '已下载'
      }
      this.lock = true
      var config = {
        onUploadProgress: (progressEvent) => {
          var complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0
          data.progress = complete
          if (data.progress == 100) {
            this.lock = false
          }
        },
      }
      const src = `${base_url}/proxy/cam/file/download?attachId=${formData.attachId}&attachName=${formData.attachName}`
      var link = document.createElement('a')
      data.fileName = formData.attachName
      link.href = src
      // link.download = res.data.data
      link.click()
      URL.revokeObjectURL(link.href)
      // commonApi.downloadFile({ ...formData, ...config }).then((res) => {
      //   const src = `${base_url}/file/download/${res.data.data}`
      //   var link = document.createElement('a')
      //   data.fileName = res.data.data
      //   link.href = src
      //   link.download = res.data.data
      //   link.click()
      //   URL.revokeObjectURL(link.href)
      // })
    },
  },
}
</script>

<style lang="less" scoped>
body {
}
.flex {
  display: flex;
  align-items: center;
}

.carList {
  background: #fff;

  .carItem {
    background: #fff;
    padding: 0.25rem 0.3rem;
    border-bottom: 1px solid #f0f0f0;
    justify-content: space-between;
    .file_lt {
      font-size: 0.26rem;
      color: #161616;
    }

    .icon-file {
      color: #999;
      margin-right: 0.1rem;
      position: relative;
      top: 1px;
    }
    .icon-download {
      font-size: 0.5rem;
      color: #409eff;
    }
    .vin {
      color: #666;
      font-size: 0.28rem;
    }
    &:last-child {
      border: none;
    }
  }
}
.footer {
  position: fixed;
  bottom: 0.5rem;
  left: 0;
  width: 100%;
  z-index: 2;
  .footerBtn {
    margin: 0.3rem;
    justify-content: space-between;
    max-width: 300px;
    margin: auto;
    .btnType {
      border-radius: 5px;
      color: #fff;
      text-align: center;
      width: 45%;
      max-width: 175px;
      padding: 15px 0;
      font-size: 14px;
      position: relative;
    }
    .selBtn {
      background: linear-gradient(316deg, #3975c6 0%, #71a4ea 100%);
      position: relative;
    }
    .uploadBtn {
      background: linear-gradient(316deg, #3975c6 0%, #71a4ea 100%);
    }
    .disable_btn {
      background: #ccc;
    }
  }
}

.file_ipt {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
  opacity: 0;
}
.downTxt {
  font-size: 0.24rem;
  color: #666;
}
.task_header {
  background: url('~@/assets/images/title_bg.png') no-repeat center;
  font-size: 0.24rem;
  height: 50px;
  background-size: 100% 100%;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 9;

  .top_title {
    position: relative;
    width: 100%;
    height: 50px;

    .top_title_back {
      position: absolute;
      left: 10px;
      line-height: 50px;
      color: #fff;
    }

    .top_title_val {
      text-align: center;
      line-height: 50px;
      color: #fff;
      font-weight: bold;
      font-size: 16px;
    }
    .task_transbox {
      position: absolute;
      right: 10px;
      top: 5px;
      color: #fff;
      z-index: 10;
      font-weight: 400;
      font-size: 10px;
      text-align: center;
      .task_trans {
        width: 24px;
        display: block;
        margin: auto;
      }
    }
  }

  .task_header_data {
    .task_header_date {
      margin-bottom: 10px;
      display: flex;
      align-items: center;

      .task_header_date_w {
        width: 12.5%;
      }

      .task_header_date_item {
        width: 12.5%;
        text-align: center;
        color: #fff;
        font-size: 14px;
      }
    }

    .task_header_followData {
      display: flex;
      align-items: center;
      color: #fff;
      margin-bottom: 10px;

      .task_header_followData_tt {
        width: 12.5%;
        text-align: center;
      }

      .task_header_followData_item {
        width: 12.5%;
        text-align: center;
        font-size: 12px;
        font-weight: bold;
      }
    }
  }
}
.mt {
  margin-top: 50px;
}
</style>
